/**
 * Copyright 2017 IBM All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an 'AS IS' BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
'use strict';
var log4js = require('log4js');
var logger = log4js.getLogger('SampleWebApp');
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http');
var util = require('util');
var app = express();
var expressJWT = require('express-jwt');
var jwt = require('jsonwebtoken');
var bearerToken = require('express-bearer-token');
var cors = require('cors');

require('./config.js');
var hfc = require('fabric-client');

var helper = require('./app/helper.js');
var createChannel = require('./app/create-channel.js');
var join = require('./app/join-channel.js');
var install = require('./app/install-chaincode.js');
var instantiate = require('./app/instantiate-chaincode.js');
var invoke = require('./app/invoke-transaction.js');
var query = require('./app/query.js');
var host = process.env.HOST || hfc.getConfigSetting('host');
var port = process.env.PORT || hfc.getConfigSetting('port');
var liftingResonseData = require('./app/liftingResponseJson.js');

var https = require('https');
var path = require('path');
var fs = require('fs');
//设置https 请求证书
var privateKey = fs.readFileSync(path.join(__dirname, './server-key.pem'), 'utf8');
var certificate = fs.readFileSync(path.join(__dirname, './server-cert.pem'), 'utf8');
var credentials = {
    key: privateKey,
    cert: certificate,
    requestCert: false,
    rejectUnauthorized: false
};
//设置https 请求 参数
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

//jdbc 数据库连接
var mysql = require('mysql');

let databaseConfig = {
    host: '172.20.10.3',
    user: 'root',
    prot: '3306',
    password: 'root',
    database: 'wsnblockchain',
};
///////////////////////////////////////////////////////////////////////////////
//////////////////////////////// SET CONFIGURATONS ////////////////////////////
///////////////////////////////////////////////////////////////////////////////
app.options('*', cors());
app.use(cors());
//support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({
    extended: false
}));
// set secret variable
app.set('secret', 'thisismysecret');
/*app.use(expressJWT({
	secret: 'thisismysecret'
}).unless({
	path: [
	'/users',
	'/ware/saveWareData',
	'/ware/queryWareData',
	'/ware/queryblockbynum',
	'/ware/querytransactions',
	'/ware/queryOrderNoListByPackageNo',
	'/ware/getChainInfo',
	'/ware/queryblockCount',
	'ware/queryInfo',
	'/ware/queryOrderCount',
	'ware/queryOrderByBlockId']
}));*/
app.use(bearerToken());
app.use(function (req, res, next) {
    logger.debug(' ------>>>>>> new request for %s', req.originalUrl);
    if (req.originalUrl.indexOf('/users') >= 0) {
        return next();
    }
    if (req.originalUrl.indexOf('/lifting/saveLiftingData') >= 0) {
        return next();
    }
    if (req.originalUrl.indexOf('/lifting/queryLiftingData') >= 0) {
        return next();
    }
    if (req.originalUrl.indexOf('/lifting/queryLiftingDataByStrTime') >= 0) {
        return next();
    }

    if (req.originalUrl.indexOf('/lifting/readLiftingByDeviceNumber') >= 0) {
        return next();
    }
    if (req.originalUrl.indexOf('/lifting/queryblockbynumOrHash') >= 0) {
        return next();
    }
    if (req.originalUrl.indexOf('/lifting/querytransactions') >= 0) {
        return next();
    }
    if (req.originalUrl.indexOf('/lifting/queryblockCount') >= 0) {
        return next();
    }
    if (req.originalUrl.indexOf('/lifting/queryblocksInfo') >= 0) {
        return next();
    }

    if (req.originalUrl.indexOf('/lifting/querytransactionsByMysqlAndChain') >= 0) {
        return next();
    }
    var token = req.token;
    jwt.verify(token, app.get('secret'), function (err, decoded) {
        if (err) {
            res.send({
                success: false,
                message: 'Failed to authenticate token. Make sure to include the ' +
                    'token returned from /users call in the authorization header ' +
                    ' as a Bearer token'
            });
            return;
        } else {
            // add the decoded user name and org name to the request object
            // for the downstream code to use
            req.username = decoded.username;
            req.orgname = decoded.orgName;
            logger.debug(util.format('Decoded from JWT token: username - %s, orgname - %s', decoded.username, decoded.orgName));
            return next();
        }
    });
});

///////////////////////////////////////////////////////////////////////////////
//////////////////////////////// START SERVER /////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
var server = https.createServer(credentials, app).listen(port, function () {});
logger.info('****************** SERVER STARTED ************************');
logger.info('***************  https://%s:%s  ******************', host, port);
server.timeout = 240000;

//全局peer 变量
var peer = 'peer0.org1.example.com';


function getErrorMessage(field) {
    var response = {
        success: false,
        message: field + ' field is missing or Invalid in the request'
    };
    return response;
}


function calRecordValid(recObj) {
    // 	liftingno, deviceNumber, strTime, eventType, characteristicData1, characteristicData2, characteristicData3

    var strData = recObj.characteristicdata1.replace(new RegExp("\'", 'g'), "\"");


    var t_type = recObj.eventtype;
    if (t_type == "updown2" || t_type == "accTooBig2") {
        var flag = checkData(strData)
        if (flag == false)
            return "red";
        else
            return "green";
    }else{
        return "red";
    }

}
///////////////////////////////////////////////////////////////////////////////
///////////////////////// REST ENDPOINTS START HERE ///////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Register and enroll user
app.post('/users', async function (req, res) {
    var username = req.body.username;
    var orgName = req.body.orgName;
    logger.debug('End point : /users');
    logger.debug('User name : ' + username);
    logger.debug('Org name  : ' + orgName);
    if (!username) {
        res.json(getErrorMessage('\'username\''));
        return;
    }
    if (!orgName) {
        res.json(getErrorMessage('\'orgName\''));
        return;
    }
    var token = jwt.sign({
        exp: Math.floor(Date.now() / 1000) + parseInt(hfc.getConfigSetting('jwt_expiretime')),
        username: username,
        orgName: orgName
    }, app.get('secret'));
    let response = await helper.getRegisteredUser(username, orgName, true);
    logger.debug('-- returned from registering the username %s for organization %s', username, orgName);
    if (response && typeof response !== 'string') {
        logger.debug('Successfully registered the username %s for organization %s', username, orgName);
        response.token = token;
        res.json(response);
    } else {
        logger.debug('Failed to register the username %s for organization %s with::%s', username, orgName, response);
        res.json({
            success: false,
            message: response
        });
    }

});
// Create Channel
app.post('/channels', async function (req, res) {
    logger.info('<<<<<<<<<<<<<<<<< C R E A T E  C H A N N E L >>>>>>>>>>>>>>>>>');
    logger.debug('End point : /channels');
    var channelName = req.body.channelName;
    var channelConfigPath = req.body.channelConfigPath;
    logger.debug('Channel name : ' + channelName);
    logger.debug('channelConfigPath : ' + channelConfigPath); //../artifacts/channel/mychannel.tx
    if (!channelName) {
        res.json(getErrorMessage('\'channelName\''));
        return;
    }
    if (!channelConfigPath) {
        res.json(getErrorMessage('\'channelConfigPath\''));
        return;
    }

    let message = await createChannel.createChannel(channelName, channelConfigPath, req.username, req.orgname);
    res.send(message);
});
// Join Channel
app.post('/channels/:channelName/peers', async function (req, res) {
    logger.info('<<<<<<<<<<<<<<<<< J O I N  C H A N N E L >>>>>>>>>>>>>>>>>');
    var channelName = req.params.channelName;
    var peers = req.body.peers;
    logger.debug('channelName : ' + channelName);
    logger.debug('peers : ' + peers);
    logger.debug('username :' + req.username);
    logger.debug('orgname:' + req.orgname);

    if (!channelName) {
        res.json(getErrorMessage('\'channelName\''));
        return;
    }
    if (!peers || peers.length == 0) {
        res.json(getErrorMessage('\'peers\''));
        return;
    }

    let message = await join.joinChannel(channelName, peers, req.username, req.orgname);
    res.send(message);
});
// Install chaincode on target peers
app.post('/chaincodes', async function (req, res) {
    logger.debug('==================== INSTALL CHAINCODE ==================');
    var peers = req.body.peers;
    var chaincodeName = req.body.chaincodeName;
    var chaincodePath = req.body.chaincodePath;
    var chaincodeVersion = req.body.chaincodeVersion;
    var chaincodeType = req.body.chaincodeType;
    logger.debug('peers : ' + peers); // target peers list
    logger.debug('chaincodeName : ' + chaincodeName);
    logger.debug('chaincodePath  : ' + chaincodePath);
    logger.debug('chaincodeVersion  : ' + chaincodeVersion);
    logger.debug('chaincodeType  : ' + chaincodeType);
    if (!peers || peers.length == 0) {
        res.json(getErrorMessage('\'peers\''));
        return;
    }
    if (!chaincodeName) {
        res.json(getErrorMessage('\'chaincodeName\''));
        return;
    }
    if (!chaincodePath) {
        res.json(getErrorMessage('\'chaincodePath\''));
        return;
    }
    if (!chaincodeVersion) {
        res.json(getErrorMessage('\'chaincodeVersion\''));
        return;
    }
    if (!chaincodeType) {
        res.json(getErrorMessage('\'chaincodeType\''));
        return;
    }
    let message = await install.installChaincode(peers, chaincodeName, chaincodePath, chaincodeVersion, chaincodeType, req.username, req.orgname)
    res.send(message);
});
// Instantiate chaincode on target peers
app.post('/channels/:channelName/chaincodes', async function (req, res) {
    logger.debug('==================== INSTANTIATE CHAINCODE ==================');
    var peers = req.body.peers;
    var chaincodeName = req.body.chaincodeName;
    var chaincodeVersion = req.body.chaincodeVersion;
    var channelName = req.params.channelName;
    var chaincodeType = req.body.chaincodeType;
    var fcn = req.body.fcn;
    var args = req.body.args;
    logger.debug('peers  : ' + peers);
    logger.debug('channelName  : ' + channelName);
    logger.debug('chaincodeName : ' + chaincodeName);
    logger.debug('chaincodeVersion  : ' + chaincodeVersion);
    logger.debug('chaincodeType  : ' + chaincodeType);
    logger.debug('fcn  : ' + fcn);
    logger.debug('args  : ' + args);
    if (!chaincodeName) {
        res.json(getErrorMessage('\'chaincodeName\''));
        return;
    }
    if (!chaincodeVersion) {
        res.json(getErrorMessage('\'chaincodeVersion\''));
        return;
    }
    if (!channelName) {
        res.json(getErrorMessage('\'channelName\''));
        return;
    }
    if (!chaincodeType) {
        res.json(getErrorMessage('\'chaincodeType\''));
        return;
    }
    if (!args) {
        res.json(getErrorMessage('\'args\''));
        return;
    }

    let message = await instantiate.instantiateChaincode(peers, channelName, chaincodeName, chaincodeVersion, chaincodeType, fcn, args, req.username, req.orgname);
    res.send(message);
});
// Invoke transaction on chaincode on target peers
app.post('/channels/:channelName/chaincodes/:chaincodeName', async function (req, res) {
    logger.debug('==================== INVOKE ON CHAINCODE ==================');
    var peers = req.body.peers;
    var chaincodeName = req.params.chaincodeName;
    var channelName = req.params.channelName;
    var fcn = req.body.fcn;
    var args = req.body.args;
    logger.debug('channelName  : ' + channelName);
    logger.debug('chaincodeName : ' + chaincodeName);
    logger.debug('fcn  : ' + fcn);
    logger.debug('args  : ' + args);
    if (!chaincodeName) {
        res.json(getErrorMessage('\'chaincodeName\''));
        return;
    }
    if (!channelName) {
        res.json(getErrorMessage('\'channelName\''));
        return;
    }
    if (!fcn) {
        res.json(getErrorMessage('\'fcn\''));
        return;
    }
    if (!args) {
        res.json(getErrorMessage('\'args\''));
        return;
    }

    let message = await invoke.invokeChaincode(peers, channelName, chaincodeName, fcn, args, req.username, req.orgname);
    res.send(message);
});
// Query on chaincode on target peers
app.get('/channels/:channelName/chaincodes/:chaincodeName', async function (req, res) {
    logger.debug('==================== QUERY BY CHAINCODE ==================');
    var channelName = req.params.channelName;
    var chaincodeName = req.params.chaincodeName;
    let args = req.query.args;
    let fcn = req.query.fcn;
    let peer = req.query.peer;

    logger.debug('channelName : ' + channelName);
    logger.debug('chaincodeName : ' + chaincodeName);
    logger.debug('fcn : ' + fcn);
    logger.debug('args : ' + args);

    if (!chaincodeName) {
        res.json(getErrorMessage('\'chaincodeName\''));
        return;
    }
    if (!channelName) {
        res.json(getErrorMessage('\'channelName\''));
        return;
    }
    if (!fcn) {
        res.json(getErrorMessage('\'fcn\''));
        return;
    }
    if (!args) {
        res.json(getErrorMessage('\'args\''));
        return;
    }
    args = args.replace(/'/g, '"');
    args = JSON.parse(args);
    logger.debug(args);

    let message = await query.queryChaincode(peer, channelName, chaincodeName, args, fcn, req.username, req.orgname);
    res.send(message);
});
//  Query Get Block by BlockNumber
app.get('/channels/:channelName/blocks/:blockId', async function (req, res) {
    logger.debug('==================== GET BLOCK BY NUMBER ==================');
    let blockId = req.params.blockId;
    let peer = req.query.peer;
    logger.debug('channelName : ' + req.params.channelName);
    logger.debug('BlockID : ' + blockId);
    logger.debug('Peer : ' + peer);
    if (!blockId) {
        res.json(getErrorMessage('\'blockId\''));
        return;
    }

    let message = await query.getBlockByNumber(peer, req.params.channelName, blockId, req.username, req.orgname);
    res.send(message);
});
// Query Get Transaction by Transaction ID
app.get('/channels/:channelName/transactions/:trxnId', async function (req, res) {
    logger.debug('================ GET TRANSACTION BY TRANSACTION_ID ======================');
    logger.debug('channelName : ' + req.params.channelName);
    let trxnId = req.params.trxnId;
    let peer = req.query.peer;
    if (!trxnId) {
        res.json(getErrorMessage('\'trxnId\''));
        return;
    }

    let message = await query.getTransactionByID(peer, req.params.channelName, trxnId, req.username, req.orgname);
    res.send(message);
});
// Query Get Block by Hash
app.get('/channels/:channelName/blocks', async function (req, res) {
    logger.debug('================ GET BLOCK BY HASH ======================');
    logger.debug('channelName : ' + req.params.channelName);
    let hash = req.query.hash;
    let peer = req.query.peer;
    if (!hash) {
        res.json(getErrorMessage('\'hash\''));
        return;
    }

    let message = await query.getBlockByHash(peer, req.params.channelName, hash, req.username, req.orgname);
    res.send(message);
});
//Query for Channel Information
app.get('/ware/getChainInfo', async function (req, res) {
    logger.debug('================ GET CHANNEL INFORMATION ======================');
    logger.debug('channelName : ' + req.params.channelName);
    var channelName = 'mychannel';

    let message = await query.getChainInfo(peer, channelName, 'Jim', 'Org1');

    logger.debug('message============' + JSON.stringify(message));
    var MessageJSONData = JSON.parse(message);
    var heightJSONData = eval('MessageJSONData.' + 'height');
    console.log(heightJSONData);
    var low = eval('heightJSONData.' + 'low');
    console.log(low);
    res.send(low);
});
//Query for Channel instantiated chaincodes
app.get('/channels/:channelName/chaincodes', async function (req, res) {
    logger.debug('================ GET INSTANTIATED CHAINCODES ======================');
    logger.debug('channelName : ' + req.params.channelName);
    let peer = req.query.peer;

    let message = await query.getInstalledChaincodes(peer, req.params.channelName, 'instantiated', req.username, req.orgname);
    res.send(message);
});
// Query to fetch all Installed/instantiated chaincodes
app.get('/chaincodes', async function (req, res) {
    var installType = req.query.type;
    logger.debug('================ GET INSTALLED CHAINCODES ======================');

    let message = await query.getInstalledChaincodes(peer, null, 'installed', req.username, req.orgname)
    res.send(message);
});
// Query to fetch channels
app.get('/channels', async function (req, res) {
    logger.debug('================ GET CHANNELS ======================');
    logger.debug('peer: ' + req.query.peer);
    if (!peer) {
        res.json(getErrorMessage('\'peer\''));
        return;
    }

    let message = await query.getChannels(peer, req.username, req.orgname);
    res.send(message);
});


// Query Get Block by Hash [还没做]
app.get('/ware/queryblockbyhash', async function (req, res) {
    logger.debug('================ GET BLOCK BY HASH ======================');
    // logger.debug('channelName : ' + req.params.channelName);
    let hash = req.query.hash;
    // let peer = req.query.peer;
    if (!hash) {
        res.json(getErrorMessage('\'hash\''));
        return;
    }

    let message = await query.getBlockByHash(peer, "mychannel", hash, 'Jim', 'Org1');
    res.send(message);
});


//  Query Get Block by BlockNumber
app.post('/lifting/queryblockbynumOrHash', async function (req, res) {
    logger.debug('==================== GET BLOCK BY NUMBER ==================');
    let blockId = req.body.blockId;
    let blockHash = req.body.blockHash;
    let transectionId = req.body.transectionId;
    // let peer = req.query.peer;
    //logger.debug('channelName : ' + req.params.channelName);

    let message = await query.getChainInfo(peer, "mychannel", 'Jim', 'Org1');
    logger.debug('message============' + JSON.stringify(message));
    var MessageJSONData = JSON.parse(JSON.stringify(message));
    var heightJSONData = eval('MessageJSONData.' + 'height');
    var low = eval('heightJSONData.' + 'low');
    logger.debug('BlockID : ' + blockId);
    logger.debug('Peer : ' + peer);
    if (!blockId && !blockHash && !transectionId) {
        var responseDataNull = {
            'code': 500,
            'data': '查询条件不可以为空！'
        }
        res.send(responseDataNull);
        return;
    }
    try {
        if (blockId) {
            if (blockId >= low) {
                var responseDataError = {
                    'code': 500,
                    'data': '该区块不存在！'
                }
                res.send(responseDataError);
                return;
            }
            let message = await query.getBlockByNumber(peer, "mychannel", blockId, 'Jim', 'Org1');
            let transactionNum = message.data.data.length;
            logger.debug(transactionNum);
            res.send(message);
            return;
        } else if (blockHash) {
            let message = await query.getBlockByHash(peer, 'mychannel', new Buffer(blockHash, "hex"), 'Jim', 'Org1');
            res.send(message);
            return;
        } else {
            logger.debug('tx_id============================' + transectionId);
            let message = await query.getBlockByTxID(transectionId, 'mychannel', peer, 'Jim', 'Org1');
            res.send(message);
        }
    } catch (Error) {
        var responseDataError = {
            'code': 500,
            'data': Error.toString()
        }
        res.send(responseDataError)
    }
});
// Query Get Transaction by Transaction ID [还没做]
app.post('/lifting/querytransactions', async function (req, res) {
    logger.debug('================ GET TRANSACTION BY TRANSACTION_ID ======================');
    //logger.debug('channelName : ' + req.params.channelName);
    let trxnId = req.body.trxnId;
    var response;
    // let peer = req.query.peer;
    if (!trxnId) {

        logger.debug("为空！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！")
        response = {
            "code": "500",
            "message": "交易id为空！"
        }
        res.send(response);
        return;
    }
    try {
        let message = await query.getTransactionByID(peer, "mychannel", trxnId, 'Jim', 'Org1');
        res.send(message);
        return;
    } catch (error) {
        response = {
            "code": "500",
            "message": error.toString()
        }
        res.send(response)
    }
});



// 区块链可视化交易节点
app.post('/lifting/querytransactionsByMysqlAndChain', async function (req, res) {
    logger.debug('================ GET TRANSACTION BY TRANSACTION_ID ======================');
    let trxnId = req.body.trxnId;
    logger.debug('trxnid================' + trxnId);
    if (!trxnId) {
        res.json(getErrorMessage('\'trxnId\''));
        return;
    }

    let message = await query.getTransactionByID(peer, "mychannel", trxnId, 'Jim', 'Org1');

    logger.debug("message =" + JSON.stringify(message));
    var txData = JSON.parse(message.transactionEnvelope.payload.data.actions[0].payload.action.proposal_response_payload.extension.results.ns_rwset[0].rwset.writes[1].value);

    //利用mysql 查询交易id 以及 区块id
    var jdbcResult = '';
    var isReceived;
    isReceived = false;
    var addSql = 'SELECT * FROM union_data_block_info where tx_id = ?';
    var addSqlParams = [trxnId];
    var connection = mysql.createConnection(databaseConfig);
    connection.query(addSql, addSqlParams, function (error, results, fields) {
        if (error)
            logger.debug(error);
        else {
            logger.debug('The result is: ', results);
            jdbcResult = results;
        }
        isReceived = true;
    });

    while (!isReceived) {
        require('deasync').sleep(100);
    }
    var result0 = JSON.stringify(jdbcResult[0]).replace("RowDataPacket ", "")
    var jdbcLifting = JSON.parse(result0)
    txData["tx_id"] = jdbcLifting.tx_id;

    txData["blocknumber"] = jdbcLifting.block_number;

    res.send(txData);
});



//查询区块总量
app.post('/lifting/queryblockCount', async function (req, res) {
    logger.debug('================ GET CHANNEL BLOCK COUNT ======================');
    logger.debug('channelName : ' + req.params.channelName);
    var channelName = 'mychannel';
    let message = await query.getChainInfo(peer, channelName, 'Jim', 'Org1');

    logger.debug('message============' + JSON.stringify(message));
    var MessageJSONData = JSON.parse(JSON.stringify(message));
    var heightJSONData = eval('MessageJSONData.' + 'height');
    var low = eval('heightJSONData.' + 'low');
    res.send(JSON.stringify(low));
});






// Invoke transaction on chaincode on target peers
app.post('/lifting/saveLiftingData', async function (req, res) {
    logger.debug('==================== INVOKE ON CHAINCODE (lifting)  ==================');
    var response = new liftingResonseData();
    // var peers = ["peer0.org1.example.com","peer0.org2.example.com"];
    var chaincodeName = 'lifting';
    var channelName = 'mychannel';
    var fcn = 'initLifting';
    var liftingHouse_req = req.body;
    //考虑到树莓派传递数据接口传递过来的并不是一个jsonObject, 需要转义等操作
    var beforeSubString = JSON.stringify(liftingHouse_req);

    var endStr = beforeSubString.substring(beforeSubString.length - 5, beforeSubString.length)

    logger.debug('endStr=' + endStr)
    if (endStr == '":""}') {
        logger.debug('JSON.stringify(req.body)============' + beforeSubString);
        var BeforeEscapingString = beforeSubString.substr(2, beforeSubString.length - 7);
        var jsonString = BeforeEscapingString.replace(new RegExp("\\\\\"", "gm"), "\"");
        liftingHouse_req = JSON.parse(jsonString);
    }
    logger.debug('JSON.stringify(req.body)============' + beforeSubString);
    if (!liftingHouse_req) {
        response.setResponseStatus("500")
        response.setResponseMessage("请求参数为空！")
        res.send(response.getResponseData());
        return;
    }
    if (!liftingHouse_req.BODY.deviceNumber) {
        response.setResponseStatus("500");
        response.setResponseMessage("deviceNumber请求参数为空！")
        res.send(response.getResponseData());
        return;
    }

    if (!liftingHouse_req.BODY.strTime) {
        response.setResponseStatus("500")
        response.setResponseMessage("strTime请求参数为空！")
        res.send(response.getResponseData());
        return;

    }

    if (!liftingHouse_req.BODY.eventType) {
        response.setResponseStatus("500")
        response.setResponseMessage("strTime请求参数为空！")
        res.send(response.getResponseData());
        return;

    }

    if (!liftingHouse_req.BODY.characteristicData1) {
        response.setResponseStatus("500")
        response.setResponseMessage("characteristicData1请求参数为空！")
        res.send(response.getResponseData());
        return;
    }
    if (!liftingHouse_req.BODY.characteristicData2) {
        response.setResponseStatus("500")
        response.setResponseMessage("characteristicData2请求参数为空！")
        res.send(response.getResponseData());
        return;
    }
    if (!liftingHouse_req.BODY.characteristicData3) {
        response.setResponseStatus("500")
        response.setResponseMessage("characteristicData2请求参数为空！")
        res.send(response.getResponseData());
        return;
    }
    logger.debug('channelName  : ' + channelName);
    logger.debug('chaincodeName : ' + chaincodeName);
    logger.debug('fcn  : ' + fcn);
    logger.debug('deviceNumber  : ' + liftingHouse_req.BODY.deviceNumber);
    logger.debug('strTime  : ' + liftingHouse_req.BODY.strTime);
    logger.debug('eventType  : ' + liftingHouse_req.BODY.eventType);
    logger.debug('characteristicData1  : ' + liftingHouse_req.BODY.characteristicData1);
    logger.debug('characteristicData2  : ' + liftingHouse_req.BODY.characteristicData2);
    logger.debug('characteristicData3  : ' + liftingHouse_req.BODY.characteristicData3);

    //给数据添加一条记录
    var timestamp = new Date().getTime();
    var Num = "";
    for (var i = 0; i < 6; i++) {
        Num += Math.floor(Math.random() * 10);
    }

    var liftingno = timestamp + Num;
    logger.debug('liftingno  : ' + liftingno);
    var args = [liftingno, liftingHouse_req.BODY.deviceNumber + '', liftingHouse_req.BODY.strTime + '', liftingHouse_req.BODY.eventType + '', liftingHouse_req.BODY.characteristicData1 + '',
        liftingHouse_req.BODY.characteristicData2 + '', liftingHouse_req.BODY.characteristicData3 + ''
    ];
    let message = "";
    try {
        message = await invoke.invokeChaincode(peer, channelName, chaincodeName, fcn, args, 'Jim', 'Org1');
        logger.debug('入链链码调用返回值  : ' + message);
    } catch (Error) {
        response.setResponseStatus("500");
        response.setResponseMessage("操作特征数据入链失败！");
        response.setLiftingNo("");
        response.setTransactionId("");
        res.send(response.getResponseData());
        return;
    }
    //再返回数据之前jdbc操作
    //查询
    let blockInfo = await query.getChainInfo(peer, channelName, 'Jim', 'Org1');
    var MessageJSONData = JSON.parse(JSON.stringify(blockInfo));
    var heightJSONData = eval('MessageJSONData.' + 'height');
    var low = eval('heightJSONData.' + 'low');

    //数据入库mysql
    var addSql = 'INSERT INTO union_data_block_info (lifting_id, block_number, tx_id) VALUES(?, ?, ?)';
    var addSqlParams = [liftingno, +low - 1, message];
    var connection = mysql.createConnection(databaseConfig);
    connection.query(addSql, addSqlParams, function (error, results, fields) {
        if (error) throw error;
        console.log('The result is: ', results);
    });
    response.setResponseStatus("200");
    response.setResponseMessage("操作特征数据入链成功！");
    response.setLiftingNo(liftingno);
    response.setTransactionId(message);
    response.setBlockNumber(+low - 1);
    logger.debug("返回值=" + JSON.stringify(response.getResponseData()));


    var strUrl = "https://10.16.6.101:8443/wsnblockchain/user/websocket.json?topic=keshih";
    if (req.protocol === 'https') {
        https.get(strUrl, (res) => {

            console.log("strUrl" + strUrl);
        console.log('statusCode:', res.statusCode);
        console.log('headers:', res.headers);

        res.on('data', (d) => {
            process.stdout.write(d);
        console.log("返回内容" + d)

    });
    }).on('error', (e) => {
            console.error(e);
    });
    }

    res.send(response.getResponseData());
});

//根据数据id 查询
app.post('/lifting/queryLiftingData', async function (req, res) {
    logger.debug('==================== QUERY ON CHAINCODE (lifting)  ==================');
    var chaincodeName = 'lifting';
    var channelName = 'mychannel';
    var fcn = 'readLifting';
    var lifting_req = req.body;

    logger.debug('channelName  : ' + channelName);
    logger.debug('chaincodeName : ' + chaincodeName);
    logger.debug('fcn  : ' + fcn);
    logger.debug('body: ' + req.body);
    logger.debug('body: ' + JSON.stringify(req.body));

    var response = new liftingResonseData();
    if (!lifting_req.BODY.liftingNo) {
        response.setResponseStatus("500")
        response.setResponseMessage("起吊数据id 为空！")
        res.send(response.getResponseData());
        return;
    }
    logger.debug('liftingNo  : ' + lifting_req.BODY.liftingNo);
    var args = [lifting_req.BODY.liftingNo];

    let message = await query.queryChaincode(peer, channelName, chaincodeName, args, fcn, 'Jim', 'Org1');
    logger.debug(message);
    //正则匹配{}
    let result1 = message.replace(lifting_req.BODY.liftingNo + " now has ", "");
    let result = result1.replace(" after the move", "");

    logger.debug("result=" + result)

    if (result == "") {
        response.setResponseStatus("500")
        response.setResponseMessage("查询结果为空！")
        res.send(response.getResponseData());
        return;
    }
    var jsonResponse = JSON.parse(result);
    if (eval('jsonResponse.' + 'Error')) {
        response.setResponseStatus("500")
        response.setResponseMessage("起吊数据id 为空！")
        res.send(response.getResponseData());
        return;
    };
    res.send(jsonResponse);
});


//根据时间段查询
app.post('/lifting/queryLiftingDataByStrTime', async function (req, res) {
    logger.debug('==================== QUERY ON CHAINCODE (lifting)  ==================');
    var chaincodeName = 'lifting';
    var channelName = 'mychannel';
    var fcn = 'readLiftingByTime';
    var lifting_req = req.body;

    logger.debug('channelName  : ' + channelName);
    logger.debug('chaincodeName : ' + chaincodeName);
    logger.debug('fcn  : ' + fcn);
    logger.debug('body: ' + req.body);
    logger.debug('body: ' + JSON.stringify(req.body));

    var response = new liftingResonseData();
    if (!lifting_req.BODY.firstTime) {
        response.setResponseStatus("500")
        response.setResponseMessage("起始时间为空！")
        res.send(response.getResponseData());
        return;
    }

    if (!lifting_req.BODY.lastTime) {
        response.setResponseStatus("500")
        response.setResponseMessage("结束时间为空！")
        res.send(response.getResponseData());
        return;
    }
    lifting_req.BODY.firstTime = lifting_req.BODY.firstTime.replace("T", " ")
    lifting_req.BODY.lastTime = lifting_req.BODY.lastTime.replace("T", " ")
    logger.debug('firstTime  : ' + lifting_req.BODY.firstTime);
    logger.debug('lastTime  : ' + lifting_req.BODY.lastTime);
    var args = [lifting_req.BODY.firstTime, lifting_req.BODY.lastTime];

    let message = await query.queryChaincode(peer, channelName, chaincodeName, args, fcn, 'Jim', 'Org1');
    logger.debug("message=" + message);
    //正则匹配{}
    let result1 = message.replace(lifting_req.BODY.firstTime + " now has ", "");
    let result = result1.replace(" after the move", "");
    logger.debug("result=" + result);
    if (result == "null") {
        res.send(JSON.parse(JSON.stringify(arrResult)));
    }

    var arr = JSON.parse(result);
    var arrResult = new Array();
    var promiseArray = new Array();
    for (var j = 0; j < arr.length; j++) {
        var ligting_id = arr[j].liftingno;
        //利用mysql 查询交易id 以及 区块id
        var addSql = 'SELECT * FROM union_data_block_info where lifting_id = ?';
        var addSqlParams = [ligting_id];
        var promise = jsbcUtils(addSql, addSqlParams);
        promiseArray.push(promise)
    }

    Promise.all(promiseArray).then(
        (ress) => {
        for (var k = 0; k < ress.length; k++) {
        var jsonLifting = arr[k];
        if (ress[k].length == 0) {
            jsonLifting["blocknumber"] = "";
            jsonLifting["tx_id"] = "";
            jsonLifting["bgcolor"] = "pink";
        } else {
            var result0 = JSON.stringify(ress[k]).replace("RowDataPacket ", "")
            var jdbcLifting = JSON.parse(result0)
            jsonLifting["blocknumber"] = jdbcLifting.block_number;
            jsonLifting["tx_id"] = jdbcLifting.tx_id;
            jsonLifting["bgcolor"] = "green";
        }
        jsonLifting["bgcolor"] = calRecordValid(jsonLifting)
        arrResult.push(jsonLifting);
    }
    res.send(JSON.parse(JSON.stringify(arrResult)));
})
});




//区块链可视化数据提供
app.get('/lifting/queryblocksInfo/', async function (req, res) {
    var blockId = req.query.blockId;
    var response = []
    var channelName = 'mychannel';
    let message = await query.getChainInfo(peer, channelName, 'Jim', 'Org1');
    logger.debug('message============' + JSON.stringify(message));
    var MessageJSONData = JSON.parse(JSON.stringify(message));
    var heightJSONData = eval('MessageJSONData.' + 'height');
    var low = eval('heightJSONData.' + 'low');
    logger.error("当前区块高度" + low);


    if (!blockId) {

        if (low >= 36) {
            blockId = low - 30
        } else {
            blockId = 6;
        }
    } else if (blockId == low - 1) {
        logger.error('没有区块更新');
        res.send(response);
        return;
    } else {
        blockId++;
    }

    var sumStr = '';
    for (var o = blockId; o < low; o++) {

        if (o == low - 1) {
            //说明是最后一块， 我们需要拿到最后一块的hash
            let message = await query.getChainInfo(peer, channelName, 'Jim', 'Org1');
            var str = JSON.stringify(message)
            var jsonStr = JSON.parse(str);
            var currentBlockHash = jsonStr.currentBlockHash.buffer.data;
            logger.error('10 DEC===============' + currentBlockHash);
            for (var z = 4; z < 36; z++) {
                var strhex = currentBlockHash[z].toString(16);
                sumStr += strhex;
            }
            logger.error('16 HEX===============' + sumStr);

        }
        for (var m = 0; m < response.length; m++) {
            if (response[m].blockId == o - 1) {
                response[m]["current_hash"] = previous_hash;
            };
        };
        let block = await query.getBlockByNumber(peer, "mychannel", o, 'Jim', 'Org1');
        var previous_hash = block.header.previous_hash;

        logger.error("上一块区块hash值===================================》" + previous_hash);
        var dataArr = block.data.data;
        var arr = new Array();
        for (var i = 0; i < dataArr.length; i++) {
            var trxnId = dataArr[i].payload.header.channel_header.tx_id;
            logger.debug('交易号' + trxnId);

            //交易不存在
            if (!trxnId) {
                logger.error('tx_id为空')
                continue;
            };
            //根据交易id查询订单信息
            let transaction = await query.getTransactionByID(peer, "mychannel", trxnId, 'Jim', 'Org1');
            var data1Arr1 = transaction.transactionEnvelope.payload.data.actions;
            var data2Arr1 = data1Arr1[0].payload.action.proposal_response_payload.extension.results.ns_rwset;
            console.log(data2Arr1);
            for (var j = 0; j < data2Arr1.length; j++) {
                if (data2Arr1[j].namespace == 'lifting') {
                    var data3Arr1 = data2Arr1[j].rwset.writes;
                    for (var k = 0; k < data3Arr1.length; k++) {
                        if (data3Arr1[k].value.substr(0, 1) == "{") {
                            var strOrderData1 = data3Arr1[k].value;
                            var jsonOrderData1 = JSON.parse(strOrderData1);
                            jsonOrderData1["tx_id"] = trxnId;
                            jsonOrderData1["blockId"] = o;
                            jsonOrderData1["bgcolor"] = calRecordValid(jsonOrderData1);
                            if (o == low - 1) {
                                jsonOrderData1["current_hash"] = sumStr;
                            }
                            response.push(jsonOrderData1);
                        }
                    }
                }
            }
        }
    }
    res.send(response);
});


/**
 * 根据设备号查询特征数据
 */
app.post('/lifting/readLiftingByDeviceNumber', async function (req, res) {
    logger.debug('==================== QUERY ON CHAINCODE (lifting)  ==================');
    var chaincodeName = 'lifting';
    var channelName = 'mychannel';
    var fcn = 'readLiftingByDeviceNumber';
    var lifting_req = req.body;

    logger.debug('channelName  : ' + channelName);
    logger.debug('chaincodeName : ' + chaincodeName);
    logger.debug('fcn  : ' + fcn);
    logger.debug('body: ' + req.body);
    logger.debug('body: ' + JSON.stringify(req.body));

    var response = new liftingResonseData();
    //	if (!lifting_req.BODY.deviceNumber) {
    //		response.setResponseStatus("500")
    //		response.setResponseMessage("起吊数据设备号为空！")
    //		res.send(response.getResponseData());
    //		return;
    //	}
    logger.debug('deviceNumber  : ' + lifting_req.BODY.deviceNumber);
    logger.debug('bookmark  : ' + lifting_req.BODY.bookmark);
    var args = [lifting_req.BODY.deviceNumber, lifting_req.BODY.bookmark];
    let message = await query.queryChaincode(peer, channelName, chaincodeName, args, fcn, 'Jim', 'Org1');
    let result1 = message.replace(lifting_req.BODY.deviceNumber + " now has ", "");

    logger.debug('区块链接口返回结果：' + result1);
    let result = result1.replace(" after the move", "");
    var liftingArrayStringJson = JSON.parse(result)
    var resultJson = liftingArrayStringJson.liftingArrayString;
    var arr = [];
    for (var i = 0; i < resultJson.length; i++) {
        arr.push(resultJson[i].Record)
    }
    var arrResult = new Array();
    var promiseArray = new Array();
    for (var j = 0; j < arr.length; j++) {
        var ligting_id = arr[j].liftingno;
        //利用mysql 查询交易id 以及 区块id
        var addSql = 'SELECT * FROM union_data_block_info where lifting_id = ?';
        var addSqlParams = [ligting_id];
        var promise = jsbcUtils(addSql, addSqlParams);
        promiseArray.push(promise)
    }

    Promise.all(promiseArray).then(
        (ress) => {
        for (var k = 0; k < ress.length; k++) {
        var jsonLifting = arr[k];
        if (ress[k].length == 0) {
            jsonLifting["blocknumber"] = "";
            jsonLifting["tx_id"] = "";
            jsonLifting["bgcolor"] = "pink";
        } else {
            var result0 = JSON.stringify(ress[k]).replace("RowDataPacket ", "")
            var jdbcLifting = JSON.parse(result0)
            jsonLifting["blocknumber"] = jdbcLifting.block_number;
            jsonLifting["tx_id"] = jdbcLifting.tx_id;
            jsonLifting["bgcolor"] = "green";
        }
        jsonLifting["bgcolor"] = calRecordValid(jsonLifting);
        arrResult.push(jsonLifting);
    }
    var liftingArray = {
        "bookmark": liftingArrayStringJson.bookmark,
        "liftingArrayData": JSON.parse(JSON.stringify(arrResult))
    }
    res.send(liftingArray);
}
)
});


/**
 *
 * @param {sql语句} sql
 * @param {sql 查询条件} addSqlParams
 */
function jsbcUtils(sql, addSqlParams) {
    return new Promise(function (resolve, reject) {
        //每次使用的时候需要创建链接，数据操作完成之后要关闭连接
        var connection = mysql.createConnection(databaseConfig);
        connection.connect(function (err) {
            if (err) {
                console.log('数据库链接失败');
                throw err;
            }
            //开始数据操作
            //传入三个参数，第一个参数sql语句，第二个参数sql语句中需要的数据，第三个参数回调函数
            connection.query(sql, addSqlParams, function (err, results, fields) {
                if (err) {
                    console.log('数据操作失败');
                    throw err;
                }
                //将查询出来的数据返回给回调函数
                resolve(results[0]);
                //results作为数据操作后的结果，fields作为数据库连接的一些字段
                //停止链接数据库，必须再查询语句后，要不然一调用这个方法，就直接停止链接，数据操作就会失败
                connection.end(function (err) {
                    if (err) {
                        console.log('关闭数据库连接失败！');
                        throw err;
                    }
                });
            });
        });
    });
}

function checkData(data) {
    var data_tmp = data.split(" ");
    var l1 = new Array(128);
    var l2 = new Array(128);
    var l3 = new Array(128);
    var l4 = new Array(128);
    var l5 = new Array(128);
    var l6 = new Array(128);
    var l7 = new Array(128);
    var l8 = new Array(128);
    var l9 = new Array(128);


    for (var i = 0; i < data_tmp.length; i++) {
        if (i < 128 * 1) {
            l1[i] = data_tmp[i]
        } else if (i >= 128 * 1 && i < 128 * 2) {
            l2[i - 128 * 1] = data_tmp[i];
        } else if (i >= 128 * 2 && i < 128 * 3) {
            l3[i - 128 * 2] = data_tmp[i];
        } else if (i >= 128 * 3 && i < 128 * 4) {
            l4[i - 128 * 3] = data_tmp[i];
        } else if (i >= 128 * 4 && i < 128 * 5) {
            l5[i - 128 * 4] = data_tmp[i];
        } else if (i >= 128 * 5 && i < 128 * 6) {
            l6[i - 128 * 5] = data_tmp[i];
        } else if (i >= 128 * 6 && i < 128 * 7) {
            l7[i - 128 * 6] = data_tmp[i];
        } else if (i >= 128 * 7 && i < 128 * 8) {
            l8[i - 128 * 7] = data_tmp[i];
        } else if (i >= 128 * 8 && i < 128 * 9) {
            l9[i - 128 * 8] = data_tmp[i];
        }
    }
    var q0 = new Array(128);
    q0[0] = 0;
    q0[1] = l4[0];
    q0[2] = l5[0];
    q0[3] = l6[0];


    var M0 = new Array(128);
    for (var x = 0; x < l3.length; x++) {
        var doubleM0 = new Array(3);
        doubleM0[0] = l4[x];
        doubleM0[1] = l5[x];
        doubleM0[2] = l6[x];
        M0[x] = doubleM0;
    }


    var M1 = new Array(128);
    for (var y = 0; y < l3.length; y++) {
        var doubleM1 = new Array(3);
        doubleM1[0] = 0;
        doubleM1[1] = 0;
        doubleM1[2] = 0;
        M1[y] = doubleM1;
    }

    var M2 = new Array(128);
    for (var z = 0; z < l3.length; z++) {
        var doubleM2 = new Array(3);
        doubleM2[0] = 0;
        doubleM2[1] = 0;
        doubleM2[2] = 0;
        M2[z] = doubleM2;
    }

    for (var t = 0; t < 128; t++) {
        //q1 = data_tmp([t,L+t,L*2+t]);
        var q1 = new Array(3);
        q1[0] = l1[t];
        q1[1] = l2[t];
        q1[2] = l3[t];

        //q2 = data_tmp([L*6+t,L*7+t,L*8+t]);
        var q2 = new Array(3);
        q2[0] = l7[t];
        q2[1] = l8[t];
        q2[2] = l9[t];
        var q1FangHe = Math.pow(q1[0], 2) + Math.pow(q1[1], 2) + Math.pow(q1[2], 2);
        var q3 = new Array(3);
        var q4 = new Array(3);

        if (q1FangHe >= 1) {
            q3[0] = 1;
            q3[1] = 0;
            q3[2] = 0;
            q3[3] = 0;
        } else {
            //q3 = [(1-sum(q1.^2))^.5, q1];
            q3[0] = Math.sqrt(1 - q1FangHe);
            q3[1] = q1[0];
            q3[2] = q1[1];
            q3[3] = q1[2];
        }

        var q2FangHe = Math.pow(q2[0], 2) + Math.pow(q2[1], 2) + Math.pow(q2[2], 2);
        if (q2FangHe >= 1) {

            q4[0] = 1;
            q4[1] = 0;
            q4[2] = 0;
            q4[3] = 0;
        } else {
            //q4 = [(1-sum(q2.^2))^.5, q2];
            q4[0] = Math.sqrt(1 - q2FangHe);
            q4[1] = q2[0];
            q4[2] = q2[1];
            q4[3] = q2[2];

        }

        var q5 = new Array(4);
        var q6 = new Array(4);
        q5[0] = q3[0];
        q5[1] = -q3[1];
        q5[2] = -q3[2];
        q5[3] = -q3[3];

        q6[0] = q4[0];
        q6[1] = -q4[1];
        q6[2] = -q4[2];
        q6[3] = -q4[3];

        var q7 = new Array(4);
        var q8 = new Array(4);
        q7[0] = q5[0] * q0[0] - q5[1] * q0[1] - q5[2] * q0[2] - q5[3] * q0[3];
        q7[1] = q5[0] * q0[1] + q5[1] * q0[0] + q5[2] * q0[3] - q5[3] * q0[2];
        q7[2] = q5[0] * q0[2] - q5[1] * q0[3] + q5[2] * q0[0] + q5[3] * q0[1];
        q7[3] = q5[0] * q0[3] + q5[1] * q0[2] - q5[2] * q0[1] + q5[3] * q0[0];

        q8[0] = q6[0] * q0[0] - q6[1] * q0[1] - q6[2] * q0[2] - q6[3] * q0[3];
        q8[1] = q6[0] * q0[1] + q6[1] * q0[0] + q6[2] * q0[3] - q6[3] * q0[2];
        q8[2] = q6[0] * q0[2] - q6[1] * q0[3] + q6[2] * q0[0] + q6[3] * q0[1];
        q8[3] = q6[0] * q0[3] + q6[1] * q0[2] - q6[2] * q0[1] + q6[3] * q0[0];
        var doubleM1 = M1[t];
        doubleM1[0] = q7[0] * q3[1] + q7[1] * q3[0] + q7[2] * q3[3] - q7[3] * q3[2];
        doubleM1[1] = q7[0] * q3[2] - q7[1] * q3[3] + q7[2] * q3[0] + q7[3] * q3[1];
        doubleM1[2] = q7[0] * q3[3] + q7[1] * q3[2] - q7[2] * q3[1] + q7[3] * q3[0];
        var doubleM2 = M2[t];
        doubleM2[0] = q8[0] * q4[1] + q8[1] * q4[0] + q8[2] * q4[3] - q8[3] * q4[2];
        doubleM2[1] = q8[0] * q4[2] - q8[1] * q4[3] + q8[2] * q4[0] + q8[3] * q4[1];
        doubleM2[2] = q8[0] * q4[3] + q8[1] * q4[2] - q8[2] * q4[1] + q8[3] * q4[0];
    }

    // double[] C1 = new double[M0.size()];

    var C1 = new Array(M0.length);
    for (var a = 0; a < M0.length; a++) {
        var M10 = M0[a][0] - M1[a][0];
        var M11 = M0[a][1] - M1[a][1];
        var M12 = M0[a][2] - M1[a][2];
        C1[a] = Math.sqrt(Math.pow(M10, 2) + Math.pow(M11, 2) + Math.pow(M12, 2));
    }

    var C2 = new Array(M0.length);
    for (var b = 0; b < M0.length; b++) {
        var M00 = M0[b][0] - M2[b][0];
        var M01 = M0[b][1] - M2[b][1];
        var M02 = M0[b][2] - M2[b][2];
        C2[b] = Math.sqrt(Math.pow(M00, 2) + Math.pow(M01, 2) + Math.pow(M02, 2));
    }

    var C3 = new Array(M0.length);
    for (var c = 0; c < M0.length; c++) {
        var M20 = M1[c][0] - M2[c][0];
        var M21 = M1[c][1] - M2[c][1];
        var M22 = M1[c][2] - M2[c][2];
        C3[c] = Math.sqrt(Math.pow(M20, 2) + Math.pow(M21, 2) + Math.pow(M22, 2));
    }

    var count1 = 0;
    for (var q = 0; q < C1.length; q++) {
        count1 += Math.pow(C1[q], 2);
    }

    var C4 = Math.sqrt(count1 / C1.length);
    var count2 = 0;
    for (var v = 0; v < C2.length; v++) {
        count2 += Math.pow(C2[v], 2);
    }

    var C5 = Math.sqrt(count2 / C2.length)
    var count3 = 0;
    for (var w = 0; w < C3.length; w++) {
        count3 += Math.pow(C3[w], 2);
    }
    var C6 = Math.sqrt(count3 / C3.length);
    var CO = Math.sqrt(Math.pow(C4, 2) + Math.pow(C5, 2) + Math.pow(C6 * 2, 2));
    console.log(CO);

    if (C4 > 0.05 || C5 > 0.05 || C6 > 0.025) {
        console.log("数据异常， 被篡改过")
        return false;
    } else {
        console.log("数据正常， 未曾被篡改")
        return true;
    }
}